class Admin::MainController < ApplicationController
  def index

    if params[:commit]
      # validations
      if params[:cau_hinh]['email_nhan_gop_y'].present? && !params[:cau_hinh]['email_nhan_gop_y'].blank?
        email_nhan_gop_y  = Email.new(:dia_chi => params[:cau_hinh]['email_nhan_gop_y'])
        if !email_nhan_gop_y.valid?
          flash.now[:error] = t 'email_khong_hop_le'
        else
          c = CauHinh.find_by_ten('email_khong_hop_le')
          if !c.present?
            c = CauHinh.create(:ten => 'email_nhan_gop_y', :gia_tri => email_nhan_gop_y.dia_chi)
          else
            c.gia_tri = v
          c.save
          end
        end
      end

      # save
      params[:cau_hinh].each{|k, v|
        if k.to_s != 'email_nhan_gop_y'
          if v.to_i < 1 || v.to_i.to_s != v
            flash.now[:error] =   t('cac_gia_tri_khac_phai_la_so_nguyen_lon_hon_0')
          next
          else
            c = CauHinh.find_by_ten(k)
            if !c.present?
              c = CauHinh.create(:ten => k, :gia_tri => v)
            else
            c.gia_tri = v
            c.save
            end
          end
        end

      }
    end

    @cau_hinhs = []
    @cau_hinhs << CauHinh.lay_gia_tri_hoac_khoi_tao('admin_so_luong_tren_trang', 20)
    @cau_hinhs << CauHinh.lay_gia_tri_hoac_khoi_tao('san_pham_so_luong_tren_trang', 20)
    @cau_hinhs << CauHinh.lay_gia_tri_hoac_khoi_tao('bai_viet_so_luong_tren_trang', 10)
    @cau_hinhs << CauHinh.lay_gia_tri_hoac_khoi_tao('email_nhan_gop_y', '')

  end

  def anh_upload
    dinh_dang_anh_cho_phep = ['.jpg', '.jpeg', '.gif', '.png', '.svg']
    files = Dir.glob("public/img/upload/*").select{ |f|
      dinh_dang_anh_cho_phep.include?(File.extname(f))
    }.sort
    if params[:s].present?
      files = files.select {|f| File.basename(f).include?(params[:s])}
    end
    @tong_so_anh = files.length
    @trang = (params[:page].present? && params[:page].to_i > 1 )? params[:page].to_i : 1
    @so_anh_moi_trang = CauHinh.gia_tri('admin_so_luong_tren_trang', 20).to_i;
    @index_dau_tien = (@trang - 1) * @so_anh_moi_trang
    if @trang > 1
      @trang_truoc = @trang - 1;
    end
    if @index_dau_tien < files.length
      @index_cuoi_cung = @index_dau_tien + @so_anh_moi_trang
      if @index_cuoi_cung < files.length
        @trang_sau = @trang + 1;
      end
      @index_cuoi_cung = @index_cuoi_cung < files.length ? @index_cuoi_cung : files.length - 1

      @anhs = files[@index_dau_tien..@index_cuoi_cung]
    else
      @anhs = []
    end
  end

  def upload
    if params[:commit]
      ten_goc = params[:upload][:file].original_filename
      ten_anh = Time.new().to_i.to_s + "_" + ten_goc
      thu_muc = "public/img/upload"
      path = File.join(thu_muc, ten_anh)
      File.open(path, "wb") { |f| f.write(params[:upload][:file].read) }
      flash.now[:success] = t('up_load_file_thanh_cong')
      @anh = path
    end
  end
end
